<?php

namespace backend\models;

use Yii;
use common\models\Admin;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;
use yii\web\IdentityInterface;

class User extends Admin implements IdentityInterface
{
    const STATUS_DELETED  = 0;
    const STATUS_INACTIVE = 9;
    const STATUS_ACTIVE   = 10;

    /**
     * @Notes 添加自动更新和设置时间的行为
     * @Interface behaviors
     *
     *
     * @return array
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:22
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    public function rules()
    {
        return ArrayHelper::merge(
            parent::rules(),
            [
                ['status', 'default', 'value' => self::STATUS_INACTIVE],
                ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
            ]
        );
    }

    /**
     * @Notes
     * @Interface getId
     *
     *
     * @return int|mixed|string
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:11
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @Notes
     * @Interface getAuthKey
     *
     *
     * @return string
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:11
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @Notes
     * @Interface validateAuthKey
     *
     * @param string $authKey
     *
     * @return bool
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:11
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * @Notes  Generates "remember me" authentication key
     * @Interface generateAuthKey
     *
     *
     * @throws \yii\base\Exception
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:30
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * @Notes  Generates password hash from password and sets it to the model
     * @Interface setPassword
     *
     * @param string $password
     *
     * @throws \yii\base\Exception
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:30
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * @Notes
     * @Interface findIdentity
     *
     * @param int|string $id
     *
     * @return User|IdentityInterface|null
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:11
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @Notes  Finds user by username
     * @Interface findByUsername
     *
     * @param string $username
     *
     * @return User|_User|null
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:33
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @Notes  Finds user by password reset token
     * @Interface findByPasswordResetToken
     *
     * @param string $token password reset token
     *
     * @return User|_User|null
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:33
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne(
            [
                'password_reset_token' => $token,
                'status'               => self::STATUS_ACTIVE,
            ]
        );
    }

    /**
     * @Notes  Finds user by verification email token
     * @Interface findByVerificationToken
     *
     * @param string $token
     *
     * @return User|_User|null
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:34
     */
    public static function findByVerificationToken($token)
    {
        return static::findOne(
            [
                'verification_token' => $token,
                'status'             => self::STATUS_INACTIVE,
            ]
        );
    }

    /**
     * @Notes  Finds out if password reset token is valid
     * @Interface isPasswordResetTokenValid
     *
     * @param string $token
     *
     * @return bool
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:35
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int)substr($token, strrpos($token, '_') + 1);
        $expire    = Yii::$app->params['user.passwordResetTokenExpire'];

        return $timestamp + $expire >= time();
    }

    /**
     * @Notes  Generates new password reset token
     * @Interface generatePasswordResetToken
     *
     *
     * @throws \yii\base\Exception
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:30
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString().'_'.time();
    }

    /**
     * @Notes
     * @Interface generateEmailVerificationToken
     *
     *
     * @throws \yii\base\Exception
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:38
     */
    public function generateEmailVerificationToken()
    {
        $this->verification_token = Yii::$app->security->generateRandomString().'_'.time();
    }

    /**
     * @Notes  Removes password reset token
     * @Interface removePasswordResetToken
     *
     *
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:29
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    /**
     * @Notes
     * @Interface findIdentityByAccessToken
     *
     * @param mixed $token
     * @param null $type
     *
     * @return void|IdentityInterface|null
     * @throws NotSupportedException
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:11
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * @Notes  Validates password
     * @Interface validatePassword
     *
     * @param string $password password to validate
     *
     * @return bool if password provided is valid for current user
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-18 0:30
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }
}
